<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TQSD监控</title>
	<style>
		body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f4f9;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 800px;
        }

        .sendButton {
            background-color: #007BFF;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            width: 26%;
            margin-bottom: 15px;
        }

        .sendButton:hover {
            background-color: #0056b3;
        }

        #messageBox {
            height: 420px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 10px;
            background-color: #f9f9f9;
        }

        #messageBox p {
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
            background-color: #e0f7fa;
        }
		
		#textInput {
			width: 780px;
			height: 50px;
            border: 1px solid #e0e0e0;
            background-color: #f9f9f9;
            padding: 10px;
            margin-bottom: 15px;
		}
    </style>
</head>

<body>
	<div class="container">
        <button class="sendButton" id="register">注册</button>
		<button class="sendButton" id="echo">ECHO</button>
		<button class="sendButton" id="clear">CLEAR</button>
		<input id="textInput"></input>
		<br>
		<button class="sendButton" id="sendInputText">SEND</button>
		<div id="messageBox"></div>
    </div>
    <script>
	
		
		
        // 创建 WebSocket 实例，连接到服务器
        var socket = new WebSocket('ws://139.159.218.3:9003');
		
		function registerSocket() {
			// 监听 WebSocket 连接成功事件
			socket.addEventListener('open', (event) => {
				console.log('Connected to the WebSocket server');
				appendMessage(`Connected to the server`);
				const message = '{"action":"register","selfId":"WEB"}';
				socket.send(message);
				console.log('Sent message:', message);
				appendMessage(`Sent message: ${message}`);
			});

			// 监听 WebSocket 接收到消息事件
			socket.addEventListener('message', (event) => {
				console.log('Received message:', event.data);
				appendMessage(`Received: ${event.data}`);
				try {
					const result = JSON.parse(event.data);
					console.log(result['action']);
				} catch (error) {
					console.error("Error parsing JSON:", error);
				}
			});

			// 监听 WebSocket 连接关闭事件
			socket.addEventListener('close', (event) => {
				console.log('Disconnected from the WebSocket server');
				appendMessage(`Disconnected from the server`);
				socket = new WebSocket('ws://139.159.218.3:9003');
				registerSocket()
			});

			// 监听 WebSocket 发生错误事件
			socket.addEventListener('error', (event) => {
				console.error('WebSocket error:', event);
				appendMessage(`WebSocket error occurred`);
			});
		}
		registerSocket()
		document.getElementById('register').addEventListener('click', () => {
            if (socket.readyState === WebSocket.OPEN) {
                const message = '{"action":"register","selfId":"WEB"}';
                socket.send(message);
                console.log('Sent message:', message);
                appendMessage(`Sent message: ${message}`);
            } else {
                console.log('WebSocket is not open.');
                appendMessage('WebSocket is not open.');
            }
        });
		document.getElementById('echo').addEventListener('click', () => {
            if (socket.readyState === WebSocket.OPEN) {
                const message = '{"action":"echo","selfId":"WEB"}';
                socket.send(message);
                console.log('Sent message:', message);
                appendMessage(`Sent message: ${message}`);
            } else {
                console.log('WebSocket is not open.');
                appendMessage('WebSocket is not open.');
            }
        });
		document.getElementById('clear').addEventListener('click', () => {
            document.getElementById('messageBox').innerHTML = ``;
        });
		document.getElementById('sendInputText').addEventListener('click', () => {
			if (socket.readyState === WebSocket.OPEN) {
                const message = document.getElementById('textInput').value;
                socket.send(message);
                console.log('Sent message:', message);
                appendMessage(`Sent message: ${message}`);
            } else {
                console.log('WebSocket is not open.');
                appendMessage('WebSocket is not open.');
            }
        });
		// 封装一个函数用于向 messageBox 中添加消息并滚动到底部
        function appendMessage(message) {
            const messageBox = document.getElementById('messageBox');
            const p = document.createElement('p');
			
			// 获取当前时间并格式化
            const now = new Date();
			const year = now.getFullYear();
			// 获取月份，由于 getMonth 返回 0 - 11，所以要加 1，并且不足两位时前面补 0
			const month = String(now.getMonth() + 1).padStart(2, '0');
			// 获取日期，不足两位时前面补 0
			const day = String(now.getDate()).padStart(2, '0');
			// 获取小时，不足两位时前面补 0
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            const time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			
            p.textContent = `[${time}] ${message}`;
            messageBox.appendChild(p);
            // 滚动到底部
            messageBox.scrollTop = messageBox.scrollHeight;
        }
    </script>
</body>

</html>